package com.dgut.app.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dgut.common.entity.WxUser;
import com.dgut.common.mapper.WxUserMapper;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * @Author zyq
 * @Date 2022/4/25 10:49
 * @Description TODO
 * @Version 1.0
 **/
@Component
@RequiredArgsConstructor
public class WxUserDetailService implements UserDetailsService {
    private final WxUserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String openid){
        QueryWrapper<WxUser> wrapper = new QueryWrapper<>();
        wrapper.eq("open_id", openid);
        WxUser user = userMapper.selectOne(wrapper);
        WxUserDetails wxUserDetails = new WxUserDetails();
        if(ObjectUtils.isNotEmpty(user)) {
            Set<GrantedAuthority> authoritiesSet = new HashSet<>();
            authoritiesSet.add(new SimpleGrantedAuthority("ROLE_" + user.getIdentity()));
            wxUserDetails.setAuthorities(authoritiesSet);
            wxUserDetails.setOpenid(openid);
        }
        return wxUserDetails;
    }
}
